layui.use(['jquery', 'febs', 'form',  'commonJS'], function () {
    var $ = layui.jquery,
        febs = layui.febs,
        form = layui.form,
        layer = layui.layer,
        commonJS = layui.commonJS,
        $resource = $('#resource'),
        $t1=$("#t1");
    $t2=$("#t2");
    $t3=$("#t3");
    $t4=$("#t4");
    $t5=$("#t5");
    $using = $('#using'),
        $weidu=$('#weidu'),
        util = layui.util,
        $view = $('#febs-index');

    var   taskdata=   getData(ctx+"home/scheduleStatusNum");
    $t1.html(taskdata.t1+' / '+taskdata.p1);
    $t2.html(taskdata.t2+' / '+taskdata.p1);
    $t3.html(taskdata.t3 +' / '+taskdata.p3);
    $t4.html(taskdata.t4+' / '+taskdata.p4);
    $t5.html(taskdata.t5+' / '+taskdata.p5);

    var  resourceListData=getData(ctx+"home/resourceList");
    initResourceOptions($resource,resourceListData, "");
    initResourceUsing();
    inintChar();
    getShipReport();



    resourceListData.forEach(item=>{
        console.log(item.rsName);
        document.getElementById(item.rsNo).addEventListener("click", function (event) {
            if(item.rsStatus==2){
                var str=item.rsName+'从'+item.stopStartTime+'至'+item.stopStartTime
                    +'停用,原因:'+item.stopReason;
                layer.msg(str);
            }else if(item.rsStatus==1){
                febs.modal.open('查看任务', 'task/detail/' +  item.taskCode + "?type=home" , {
                    area: $(window).width() <= 750 ? ['90%', '90%'] : ['80%', '90%'],
                    btn: ['关闭'],
                    offset: ['5px', '5px'],
                    yes: function (index, layero) {
                        layer.close(index);
                    }, cancel: function () {
                    }, data: {},
                });
            }
        });
    })


    function  inintChar(){
        var resourceid=$resource.val();
        var weidu=$weidu.val();
        getResourcePlan(resourceid,weidu);
    }

    function   initResourceUsing(){
        $using.empty();
        var  str = "";
        if(resourceListData != null && resourceListData.length > 0){
            resourceListData.forEach(item => {
                str = str + '<div class="dashboard-stats2 tooltip" id=\"' + item.rsNo + '\">';
                if (item.rsStatus == 2) {
                    str = str + '<div class="dashboard-stats-item" style="margin-top:0px;background:url(/febs/images/picture/tingyong.png);background-size: 100% 100%;">';
                } else if(item.rsStatus == 3){
                    str = str + '<div class="dashboard-stats-item" style="margin-top:0px;background:url(/febs/images/picture/kongxian.png);background-size: 100% 100%;">';
                }else {
                    str = str + '<div class="dashboard-stats-item"' +
                        ' style="margin-top:0px;background:url(/febs/images/picture/zhanyong.png);background-size:' +
                        ' 100% 100%;">';
                }
                if (item.rsStatus == 2) {
                    str = str + '<h2 class="m-top-none">' + item.rsStatusName + '</h2>';
                } else {
                    str = str + '<h2 class="m-top-none">' + item.rsStatusName + '</h2>';
                }
                str = str + "<h52>" + item.rsName + "</h52></div></div>";
            });
        }
        $using.append(str);
    }



    function  getResourcePlan(resourceid,weidu){
        var   condition={resourceid:resourceid,weidu:weidu} ;
        var data= getData(ctx +"home/resourceData",condition);
        var myChart001 = echarts.init(document.getElementById('myChart001'));
        var option = {
            color: ['#00BFFF', '#DAA520'],
            title: {
                text: '资源档期负荷情况',
                subtext: '统计未来半年以内每周各资源被预约的天数'
            },
            grid: {
                left: '2%',
                right: '2%',
                bottom: '3%',
                containLabel: true
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                }
            },
            toolbox: {
                feature: {
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
            xAxis: {
                name:weidu,
                type: 'category',
                data: data.weeks,
            },
            yAxis: {
                type: 'value',
                min: 0,
                interval: 5,
                axisLine: {
                },
                axisLabel: {
                    formatter: '{value} '
                }
            },
            dataZoom: [
                {
                    show: true,
                    start: 10,
                    end: 80
                }
            ],
            series: [
                {
                    name: '已排期天数',
                    type: 'bar',
                    stack: '排期情况',
                    data: data.workday,
                    label: {
                        normal: {
                            show: true
                        }
                    }
                },
                {
                    name: '可预约天数',
                    type: 'bar',
                    stack: '排期情况',
                    itemStyle: { color: 'rgba(0, 255, 127, 0.4)' },
                    data: data.unworkday,
                    label: {
                        normal: {
                            show: true
                        }
                    }
                }
            ]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart001.setOption(option);
    }


    function   getShipReport(){
        // 船模加工工作量统计
        var data= getData(ctx +"home/shipData",{});
        var myChart003= echarts.init(document.getElementById('myChart003'));
        // 指定图表的配置项和数据
        var option = {
            color: ['#00BFFF', '#DAA520'],
            title: {
                text: '船模加工数量统计',
                subtext: '统计一年以内的每月加工船模的数量'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                }
            },
            toolbox: {
                feature: {
                    magicType: { show: true, type: ['line', 'bar'] },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
            xAxis: {
                type: 'category',
                data: data.yearMonth,
            },
            yAxis: {
                type: 'value',
                min: 0,
                interval: 5,
                axisLine: {
                },
                axisLabel: {
                    formatter: '{value} '
                }
            },
            dataZoom: [
                {
                    show: true,
                    start: 10,
                    end: 80
                }
            ],
            series: [
                {
                    name: '船模',
                    type: 'line',
                    data: data.num,
                    label: {
                        normal: {
                            show: true,
                            position: 'top'
                        }
                    }
                }
            ]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart003.setOption(option);

    }


    function   getData(url,condition){
        var result={};
        $.ajax({
            type: "get",
            dataType: "json",
            url: url,
            data: condition,
            cache: false,
            async: false,
            success: function (data) {
                result = data || {};
            },
        });
        return result;
    }


    $resource.on('change',function (data){
        var  resourceid=   data.target.value;
        var  weidu=$weidu.val();
        getResourcePlan(resourceid,weidu);

    });

    $weidu.on('change',function (data){
        var resourceid=$resource.val();
        var weidu=data.target.value;
        getResourcePlan(resourceid,weidu);
    });

    function initResourceOptions(element, data,  callBack) {
        $(element).empty();
        $(element).append(`<option value="">请选择</option>`);
        if (data != null && data.length > 0) {
            var i=0;
            data.forEach(item => {
                if (i==0) {
                    element.append(`<option value="${item.id}"  selected>${item.rsName}</option>`)
                } else {
                    element.append(`<option value="${item.id}" >${item.rsName}</option>`)
                }
                i++;
            });
        }
        if (typeof (callBack) === "function") {
            callBack(result);
        }
        layui.form.render('select');
    }

    febs.get(ctx + 'index/' + currentUser.userName, null, function (r) {
        handleSuccess(r.data);
    });

    function handleSuccess(data) {
        var hour = new Date().getHours();
        var time = hour < 6 ? '早上好' : (hour <= 11 ? '上午好' : (hour <= 13 ? '中午好' : (hour <= 18 ? '下午好' : '晚上好')));

        //var welcomeMessage = time + '，<a id="febs-index-user">' + currentUser.userName + '</a>，' + welcomeArr[index];
        //   var welcomeMessage = time + '，<a id="febs-index-user">' + currentUser.uname + '</a>';
        var welcomeMessage = time + ',欢迎登录试验排期系统!' ;
        $view
            // .find('#today-ip').text(data.todayIp).end()
            // .find('#today-visit-count').text(data.todayVisitCount).end()
            //  .find('#total-visit-count').text(data.totalVisitCount).end()
            //  .find('#user-dept').text(currentUser.deptName ? currentUser.deptName : '暂无所属部门').end()
            //   .find('#user-role').text(currentUser.roleName ? currentUser.roleName : '暂无角色').end()
            //   .find('#last-login-time').text(currentUser.lastLoginTime ? currentUser.lastLoginTime : '第一次访问系统').end()
            .find('#user-avatar').attr('src', ctx + "febs/images/avatar/" + currentUser.avatar);
        $('#welcome-message').html(welcomeMessage).end()

        var currentTime = new Date().getTime();
        var yourVisitCount = [];
        var totalVisitCount = [];
        var lastTenDays = [
            util.toDateString(new Date(currentTime - 1000 * 9 * 86400), 'MM-dd'),
            util.toDateString(new Date(currentTime - 1000 * 8 * 86400), 'MM-dd'),
            util.toDateString(new Date(currentTime - 1000 * 7 * 86400), 'MM-dd'),
            util.toDateString(new Date(currentTime - 1000 * 6 * 86400), 'MM-dd'),
            util.toDateString(new Date(currentTime - 1000 * 5 * 86400), 'MM-dd'),
            util.toDateString(new Date(currentTime - 1000 * 4 * 86400), 'MM-dd'),
            util.toDateString(new Date(currentTime - 1000 * 3 * 86400), 'MM-dd'),
            util.toDateString(new Date(currentTime - 1000 * 2 * 86400), 'MM-dd'),
            util.toDateString(new Date(currentTime - 1000 * 86400), 'MM-dd'),
            util.toDateString(new Date(currentTime), 'MM-dd')
        ];


        layui.each(lastTenDays, function (k, i) {
            var contain = false;
            layui.each(data.lastSevenUserVisitCount, function (key, item) {
                if (i === item.days) {
                    yourVisitCount.push(item.COUNT);
                    contain = true;
                }
            });
            if (!contain) yourVisitCount.push(0);
            contain = false;
            layui.each(data.lastSevenVisitCount, function (key, item) {
                if (i === item.days) {
                    totalVisitCount.push(item.COUNT);
                    contain = true;
                }
            });
            if (!contain) totalVisitCount.push(0);
        });

        var options = {
            chart: {
                height: 350,
                type: 'bar',
                toolbar: {
                    show: false
                }
            },
            plotOptions: {
                bar: {
                    horizontal: false,
                    columnWidth: '32rem'
                }
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                show: true,
                width: 1,
                colors: ['transparent']
            },
            series: [{
                name: '总数',
                data: totalVisitCount
            }, {
                name: '您',
                data: yourVisitCount
            }],
            xaxis: {
                categories: lastTenDays,
                axisTicks: {
                    show: true
                },
                axisBorder: {
                    show: true,
                    color: '#f1f1f1'
                }
            },
            fill: {
                opacity: 1
            },
            title: {
                text: '近10天系统访问记录',
                align: 'left',
                style: {
                    color: 'rgba(0, 0, 0, .65)'
                }
            },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return "访问次数 " + val + " 次"
                    }
                }
            },
            grid: {
                row: {
                    colors: ['transparent', 'transparent'],
                    opacity: 0.2
                },
                borderColor: '#f1f1f1'
            }
        };

        /*  new ApexCharts(
              document.querySelector("#chart"),
              options
          ).render();*/
    }

    $view.on('click', '#febs-index-user',function () {
        febs.navigate("/user/profile");
    })





});